#include "include.h"
#include "api_alg.h"
#include "nr_far.h"
/*
 * 文件名称: nr_far.c
 * 功能描述: 本文件为软件NR_FAR轻量级降噪处理模块
 ****************************************************************************************
    code : 待测
    buf  : 待测
    time : 待测
 */
#if NR_FAR_EN

uint8_t wireless_mic_nr_noise_thr = NR_FAR_PAR_NOISE_THR;
uint8_t wireless_mic_nr_level = NR_FAR_PAR_LEVEL;

static nr_far_mic_cfg_t nr_far_mic_cfg AT(.buf.nr_far);
uint8_t nr_far_cirbuf[2048] AT(.buf.nr_far);
uint8_t nr_far_cirbuf_cache[256] AT(.buf.nr_far);
#if 0
AT(.text.nr_far_proc)
const char nr_far_info[] = "NR FAR T, samples = %d, isrcnt = %d (SR_%d)\n";
#endif
AT(.text.nr_far_proc)WEAK
void nr_far_mic_input(u8 *ptr, u32 samples, int ch_mode, void *params)
{
    if (!nr_far_mic_cfg.mute) {
        cbuf_cfg_t *nr_far_cbuf_t = &nr_far_mic_cfg.nr_far_mic_cbuf;

        cbuf_input_audio(ptr, samples, nr_far_cbuf_t);
        u16 out_samples = 128;
    //    s16 *rptr = (s16 *)nr_far_cirbuf_cache;
        ///需要做一个buff保存数据，当超过128个点时启动计算
        while(cbuf_total_samples_get(nr_far_cbuf_t) >= out_samples) {
            #if 0
            static u32 ticks = 0;
            static u32 isr_cnt = 0;
            isr_cnt++;
            if (tick_check_expire(ticks,1000)) {
                my_printf(nr_far_info, out_samples, isr_cnt, out_samples*isr_cnt);
                isr_cnt = 0;
                ticks = tick_get();
            }
            #endif // 0
            cbuf_output_audio((u8 *)nr_far_cirbuf_cache, out_samples, nr_far_cbuf_t);
            nr_far_process((s16 *)nr_far_cirbuf_cache);
            nr_far_process((s16 *) &nr_far_cirbuf_cache[128]);
            if (nr_far_mic_cfg.callback) {
                nr_far_mic_cfg.callback((u8 *)nr_far_cirbuf_cache, out_samples, ch_mode, params);
            }
        }
    }else{
        if (nr_far_mic_cfg.callback) {
            nr_far_mic_cfg.callback((u8 *)ptr, samples, ch_mode, params);
        }
    }
}

AT(.text.nr_far_set.callback)
void nr_far_mic_output_callback_set(audio_callback_t callback)
{
    nr_far_mic_cfg.callback = callback;
}

AT(.text.nr_far_set.mute)
void nr_far_mic_mute_set(uint8_t mute)
{
    nr_far_mic_cfg.mute = mute;
}

AT(.text.nr_far_init)WEAK
void nr_far_mic_init(u8 sample_rate, u16 samples)
{
    my_printf("%s %d %d\n", __func__,wireless_mic_nr_noise_thr,wireless_mic_nr_level);

    memset(&nr_far_mic_cfg, 0, sizeof(nr_far_mic_cfg_t));
    nr_far_mic_cfg.sample_rate = sample_rate;
    nr_far_mic_cfg.samples     = samples;

    nr_far_init(wireless_mic_nr_noise_thr,wireless_mic_nr_level);

    cbuf_init(&(nr_far_mic_cfg.nr_far_mic_cbuf), nr_far_cirbuf, 2048);
}

AT(.text.nr_far_set.param)
void nr_far_mic_param_set(u16 noise_thr, u16 nr_level)
{
    nr_far_init(noise_thr, nr_level);
}

AT(.text.nr_far_exit)
void nr_far_mic_exit(void)
{
    nr_far_mic_mute_set(1);
}

#endif
